import pgzrun
from vec import *
import random
import time

WIDTH = 600
HEIGHT = 440

BACK_COLOR = (0, 0, 0)

lastTime = time.time()
deltaTime = 0

rcHeight = [100, 200, 120, 80, 50, 150, 20, 160, 90, 130]
n = len(rcHeight)
rcWidth = 20
space = 10
pspd = 2

class MyRect:
    def __init__(self, lb_x, lb_y, h, clr):
        self.pos = Vec2(lb_x, lb_y)
        self.h = h
        self.clr = clr
        self.p = 0.0
        self.curState = 0   # 0: 静止，1: 移动
        self.start_pt = Vec2(0, 0)
        self.end_pt = Vec2(0, 0)

    def StartMove(self, end_pt):
        if self.curState == 1:
            return

        self.curState = 1
        self.p = 0
        self.start_pt = self.pos
        self.end_pt = end_pt

    def Move(self):
        has_finished = False

        self.p += pspd * deltaTime

        if self.p > 1.0:    
            self.p = 1.0
            has_finished = True

        self.pos = self.start_pt * (1 - self.p) + self.end_pt * self.p

        return has_finished

    def Update(self):
        if self.curState == 1:
            if self.Move() == True:
                self.curState = 0

    def Draw(self):
        rc = Rect((self.pos.x, self.pos.y - self.h), (rcWidth, self.h))
        screen.draw.filled_rect(rc, self.clr)

startX = 150
iter = startX
rcList = []

i = 1
j = 0
isSortingFinished = False
sortingState = 0 # 0: 交换数据，1: 移动矩形
gap=len(rcHeight)//2
i = gap
j = i
for item in rcHeight:
    r = 150-item*0.7
    g = 175-item*0.7
    b = 175-item*0.7
    rcList.append(MyRect(iter, HEIGHT / 4*3, item, (r, g, b)))
    iter += rcWidth
    iter += space

def bubble_swap(i):
    global rcHeight, rcList
    if i-1 == -1:
        return False
    if rcHeight[i-1] < rcHeight[i]:
        rcList[i].StartMove(rcList[i - 1].pos)
        rcList[i - 1].StartMove(rcList[i].pos)
        rcHeight[i], rcHeight[i - 1] = rcHeight[i - 1], rcHeight[i]
        rcList[i], rcList[i - 1] = rcList[i - 1], rcList[i]
        return True
    return False
    
def update():
    global lastTime, deltaTime, isSortingFinished, sortingState, i,j,rcList,gap
    curTime = time.time()
    deltaTime = curTime - lastTime
    lastTime = curTime

    if isSortingFinished == True:
        return

    if sortingState == 0:
        if bubble_swap(j) == True:
            sortingState = 1
        if j < 0 or rcHeight[j-gap]<rcHeight[i]:
            i += 1
            j=i
        j-=gap
        if i >= len(rcHeight):
            gap//=2
            i=gap
        if gap<0:
            isSortingFinished=True
    else:
        allStoped = True
        for rc  in rcList:
            rc.Update()
            if rc.curState == 1:
                allStoped = False

        if allStoped == True:
            sortingState = 0

def draw():
    screen.clear()
    screen.fill(BACK_COLOR)
    for rc in rcList:
        rc.Draw()

pgzrun.go()